package GUI;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.xml.ws.Response;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import com.cloudgarden.resource.SWTResourceManager;


/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class NewSWTApp extends org.eclipse.swt.widgets.Composite
{
	//Components of the GUI
	private Text userName;
	private Text passward;
	private Button register;
	private Label label4;
	private Label label3;
	private Text hibernatePassword;
	private Text hibernateUserName;
	private Text dropBoxPath;
	private Button choosePath;
	private Label label2;
	private Label label1;

	{
		//Register as a resource user - SWTResourceManager will
		//handle the obtaining and disposing of resources
		SWTResourceManager.registerResourceUser(this);
	}

	public NewSWTApp(Composite parent, int style)
	{
		super(parent, style);
		initGUI();
	}
	
	/**
	* Initializes the GUI.
	*/
	private void initGUI() 
	{
		try 
		{
			this.setSize(457, 247);
			FormLayout thisLayout = new FormLayout();
			this.setLayout(thisLayout);
			this.setBackground(SWTResourceManager.getColor(128, 128, 128));
			// Jigloo automatic creation of label4
			{
				label4 = new Label(this, SWT.NONE);
				FormData label4LData = new FormData();
				label4LData.left =  new FormAttachment(0, 1000, 22);
				label4LData.top =  new FormAttachment(0, 1000, 173);
				label4LData.width = 174;
				label4LData.height = 14;
				label4.setLayoutData(label4LData);
				label4.setText("enter your SQL password:");
				label4.setBackground(SWTResourceManager.getColor(128, 128, 128));
			}
			// Jigloo automatic creation of label3
			{
				label3 = new Label(this, SWT.NONE);
				FormData label3LData = new FormData();
				label3LData.left =  new FormAttachment(0, 1000, 22);
				label3LData.top =  new FormAttachment(0, 1000, 141);
				label3LData.width = 154;
				label3LData.height = 14;
				label3.setLayoutData(label3LData);
				label3.setText("enter your SQL user name:");
				label3.setBackground(SWTResourceManager.getColor(128, 128, 128));
			}
			// Jigloo automatic creation of hibernatePassword
			{
				FormData hibernatePasswordLData = new FormData();
				hibernatePasswordLData.left =  new FormAttachment(0, 1000, 202);
				hibernatePasswordLData.top =  new FormAttachment(0, 1000, 173);
				hibernatePasswordLData.width = 188;
				hibernatePasswordLData.height = 14;
				hibernatePassword = new Text(this, SWT.PASSWORD);
				hibernatePassword.setLayoutData(hibernatePasswordLData);
			}
			// Jigloo automatic creation of hibernateUserName
			{
				FormData hibernateUserNameLData = new FormData();
				hibernateUserNameLData.left =  new FormAttachment(0, 1000, 202);
				hibernateUserNameLData.top =  new FormAttachment(0, 1000, 141);
				hibernateUserNameLData.width = 188;
				hibernateUserNameLData.height = 14;
				hibernateUserName = new Text(this, SWT.NONE);
				hibernateUserName.setLayoutData(hibernateUserNameLData);
			}
			// Jigloo automatic creation of dropBoxPath
			{
				FormData dropBoxPathLData = new FormData();
				dropBoxPathLData.left =  new FormAttachment(0, 1000, 202);
				dropBoxPathLData.top =  new FormAttachment(0, 1000, 110);
				dropBoxPathLData.width = 187;
				dropBoxPathLData.height = -3;
				dropBoxPath = new Text(this, SWT.H_SCROLL);
				dropBoxPath.setLayoutData(dropBoxPathLData);
			}
			// Jigloo automatic creation of choosePath
			{
				choosePath = new Button(this, SWT.PUSH | SWT.CENTER);
				FormData choosePathLData = new FormData();
				choosePathLData.left =  new FormAttachment(0, 1000, 19);
				choosePathLData.top =  new FormAttachment(0, 1000, 107);
				choosePathLData.width = 171;
				choosePathLData.height = 24;
				choosePath.setLayoutData(choosePathLData);
				choosePath.setText("click to choose dropbox path");
				choosePath.setBackground(SWTResourceManager.getColor(0, 0, 0));
				choosePath.addMouseListener(new MouseListener() 
				{		
					@Override
					public void mouseUp(MouseEvent arg0)
					{
						String selected;
						DirectoryDialog dd = new DirectoryDialog(getShell(), SWT.OPEN);
						dd.setText("open");
						selected = dd.open();	
						if (selected == null)
							return;
						//we insert dropBoxPath the path of the chosen directory
						dropBoxPath.setText(selected);
					}
					
					@Override
					public void mouseDown(MouseEvent arg0) {}
					
					@Override
					public void mouseDoubleClick(MouseEvent arg0) {}
				});
			}
			// Jigloo automatic creation of label2
			{
				label2 = new Label(this, SWT.NONE);
				FormData label2LData = new FormData();
				label2LData.left =  new FormAttachment(0, 1000, 19);
				label2LData.top =  new FormAttachment(0, 1000, 81);
				label2LData.width = 150;
				label2LData.height = 14;
				label2.setLayoutData(label2LData);
				label2.setText("enter your password: ");
				label2.setBackground(SWTResourceManager.getColor(128, 128, 128));
			}
			// Jigloo automatic creation of label1
			{
				label1 = new Label(this, SWT.NONE);
				FormData label1LData = new FormData();
				label1LData.left =  new FormAttachment(0, 1000, 19);
				label1LData.top =  new FormAttachment(0, 1000, 49);
				label1LData.width = 127;
				label1LData.height = 14;
				label1.setLayoutData(label1LData);
				label1.setText("enter your user name: ");
				label1.setBackground(SWTResourceManager.getColor(128, 128, 128));
			}
			// Jigloo automatic creation of register
			{
				register = new Button(this, SWT.PUSH | SWT.CENTER);
				FormData registerLData = new FormData();
				registerLData.left =  new FormAttachment(0, 1000, 202);
				registerLData.top =  new FormAttachment(0, 1000, 211);
				registerLData.width = 70;
				registerLData.height = 24;
				register.setLayoutData(registerLData);
				register.setText("register");
				register.addMouseListener(new MouseListener() 
				{
					@Override
					public void mouseUp(MouseEvent arg0) 
					{
						//the case one of the fields is empty
						if(userName.getText().trim().equals("") || passward.getText().trim().equals("") 
								|| dropBoxPath.getText().trim().equals("") || hibernatePassword.getText().trim().equals("")
								|| hibernateUserName.getText().trim().equals(""))
						{
							MessageBox ms = new MessageBox(getShell(), SWT.ERROR);
							ms.setMessage("Must fill in all fields");
							ms.open();
						}
						else
						{
							String request=null,response=null;
							try
							{
								/*there is socket between this project to server project*/
								Socket socket=null;
								PrintWriter out=null;
								BufferedReader in =null;
								String host = "localhost"; 
								socket = new Socket(host,4443);
								out = new PrintWriter(socket.getOutputStream(),true);
								in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
								
								/*we send to server project the user name and password*/
								request = userName.getText();
								out.println(request);
								request = passward.getText();
								out.println(request);
								//response from the server.return false if the user name already exist.
								//else - return true
								response = in.readLine();
								
								// close connection (Order important)
								if (out != null) out.close();  
								if (in != null)  in.close();  
								if (socket!= null)  socket.close();
							}
							catch(Exception e) {}

							if (response == null || response.equals("false"))
							{
								//the case there is problem with the connection
								if (response == null)
								{
									MessageBox ms = new MessageBox(getShell(), SWT.ERROR);
									ms.setMessage("Server problems, try again later");
									ms.open();
								}
								//the case response = "false"
								else 
								{
									MessageBox ms = new MessageBox(getShell(), SWT.ERROR);
									ms.setMessage("User name already exist");
									ms.open();
								}
							}
							//the case this is a new user
							else
							{
								//these 3 commands create directories which will be created on the user computer
								new File("C:\\Program Files\\m&l_dropbox").mkdir();
								new File("C:\\userPlugIn").mkdir();
								new File("C:\\userPlugIn\\automaticTagging").mkdir();
								
								Encoder e = new Encoder();
								
								
								UpdateXml ux = new UpdateXml(hibernateUserName.getText().trim(),hibernatePassword.getText().trim());
								//updating the xml with the hibernate configuration with the 
								//user name and password of SQL of the user
								ux.update();
								try
								{
									/*creating xml file with the user name and password of the user.
									the creation of the xml file is because we want that the information 
									will not be volatile*/
									e.encode(userName.getText(), passward.getText(), dropBoxPath.getText());
								} 
								catch (Exception e1) 
								{
									e1.printStackTrace();
								}

								//creating the dropBox directory of the user
								new File(dropBoxPath.getText()+ "/DropBox").mkdir();
								
								/*copy the spy program from the disk to constant place in the computer in order to run it as a service*/
								File file1 = new File("spy");
								File file2 = new File("C:\\Program Files\\m&l_dropbox\\spy");
								try 
								{
									copyDirectory(file1, file2);
								} 
								catch (IOException e2) 
								{
									MessageBox ms = new MessageBox(getShell(), SWT.ERROR);
									ms.setMessage("the installation has encourted a problem");
									ms.open();
									System.exit(-1);
								}
								

								MessageBox ms = new MessageBox(getShell());
								ms.setMessage("you have istalled the spy program succesfuly, now you can activate the service using the tomcat symbol in the bottom of the screen\n" +
								" press ok to continue");
								ms.open(); 
								//run the batch file run.bat
								try
								{
									Runtime.getRuntime().exec("cmd /c start run.bat");
								}
								catch(Exception e1) 
								{
									e1.printStackTrace();
								}
								System.exit(0);
							}
						}
					}

					@Override
					public void mouseDown(MouseEvent arg0) {}

					@Override
					public void mouseDoubleClick(MouseEvent arg0) {}
				});
			}
			// Jigloo automatic creation of passward
			{
				FormData passwardLData = new FormData();
				passwardLData.left =  new FormAttachment(0, 1000, 202);
				passwardLData.top =  new FormAttachment(0, 1000, 81);
				passwardLData.width = 188;
				passwardLData.height = 14;
				passward = new Text(this, SWT.PASSWORD);
				passward.setLayoutData(passwardLData);
			}
			// Jigloo automatic creation of userName
			{
				FormData userNameLData = new FormData();
				userNameLData.left =  new FormAttachment(0, 1000, 202);
				userNameLData.top =  new FormAttachment(0, 1000, 49);
				userNameLData.width = 188;
				userNameLData.height = 14;
				userName = new Text(this, SWT.NONE);
				userName.setLayoutData(userNameLData);
			}
			this.layout();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/*
	 * the function copy all the content (files and directories) of sourceLocation to targetLocation.
	 * @param sourceLocation - from here we want to copy the files and dirs
	 * @param targetLocation - to here we want to copy the files and dirs
	 */
    static private void copyDirectory(File sourceLocation , File targetLocation)throws IOException 
    { 
        if (sourceLocation.isDirectory()) 
        {
        	//in this case we create the target location
            if (!targetLocation.exists()) 
            {
                targetLocation.mkdir();
            }
            
            String[] children = sourceLocation.list();
            //run over all the files in the directory sourceLocation
            for (int i=0; i<children.length; i++)
            {
            	//copy the file (or directory) from the source location to the destination
                copyDirectory(new File(sourceLocation, children[i]), new File(targetLocation, children[i]));
            }
        } 
        //sourceLocation isn't a directory.it's a file
        else 
        {    
            InputStream in = new FileInputStream(sourceLocation);
            OutputStream out = new FileOutputStream(targetLocation);
            
            // copy the bits from in stream to out stream
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) 
            {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
        }
    } 

	/**
	 * Auto-generated main method to display this 
	 * org.eclipse.swt.widgets.Composite inside a new Shell.
	 */
	public static void main(String[] args) 
	{
		Display display = Display.getDefault();
		Shell shell = new Shell(display, SWT.MIN);
		NewSWTApp inst = new NewSWTApp(shell, SWT.NULL);
		Point size = inst.getSize();
		shell.setLayout(new FillLayout());
		shell.layout();
		if(size.x == 0 && size.y == 0) 
		{
			inst.pack();
			shell.pack();
		}
		else
		{
			Rectangle shellBounds = shell.computeTrim(0, 0, size.x, size.y);
			shell.setSize(shellBounds.width, shellBounds.height);
		}
		shell.open();
		while (!shell.isDisposed()) 
		{
			if (!display.readAndDispatch())
				display.sleep();
		}
	}
}
